<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElTag, ElMessageBox, ElMessage } from 'element-plus'
import { Table } from '@/components/Table'
import {
  ucRoleListApi,
  ucRoleEditAdminApi,
  ucRoleAddApi,
  ucRoleDelAdminApi,
  ucRoleBatchDelApi
} from '@/api/uc/role'
import { ucRoleFaSetApi, ucRoleFaSeeApi } from '@/api/uc/roleFa'
import { ucFaListApi } from '@/api/uc/function'
import { useTable } from '@/hooks/web/useTableTest'
import { TableData } from '@/api/uc/sysRole/types'
import { h, ref, unref, reactive } from 'vue'
import Edit from './components/Edit.vue'
import Tree from './components/Tree.vue'
import See from './components/See.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'
// 获取字典
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
const iconFunction = useIcon({ icon: 'ep:operation' })
const iconDel = useIcon({ icon: 'ep:delete' })
const { register, tableObject, methods } = useTable<
  {
    total: number
    list: TableData[]
  },
  TableData
>({
  getListApi: ucRoleListApi,
  // delListApi: roleBatchDelApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

// 加上默认条件
tableObject.fixedSearch = { is_sys: 1 }

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'role_id',
    label: '角色ID',
    search: {
      show: true
    },
    form: {
      show: false
    }
  },
  {
    field: 'role_name',
    label: '角色名称',
    search: {
      show: true
    }
  },
  {
    field: 'is_sys',
    label: '是否系统角色',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('is', cellValue)
    },
    form: {
      component: 'Select',
      componentProps: {
        options: dict.is
      }
    },
    search: {
      show: true,
      component: 'Select',
      componentProps: {
        options: dict.is
      }
    }
  },
  {
    field: 'is_stop',
    label: '是否停用',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return h(
        ElTag,
        {
          type: cellValue == '0' ? 'success' : cellValue == '1' ? 'warning' : 'danger'
        },
        () => (cellValue == '0' ? '启用' : cellValue == '1' ? '停用' : '未知')
      )
    },
    form: {
      component: 'Select',
      componentProps: {
        options: [
          {
            label: '启用',
            value: '0'
          },
          {
            label: '停用',
            value: '1'
          }
        ]
      }
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    form: {
      show: false,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'note',
    label: '描述',
    table: {},
    form: {
      component: 'Input',
      componentProps: {
        type: 'textarea',
        rows: 5
      },
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'action',
    width: '280px',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const delLoading = ref(false)

const treeProps = ref({})

const treeData = ref([])

const treeKey = ref('')

const delData = async () => {
  const { getSelections } = methods
  const selections = await getSelections()
  const ids = selections.map((v) => v.role_id)
  delLoading.value = true
  ElMessageBox.confirm(t('common.delMessage'), t('common.delWarning'), {
    confirmButtonText: t('common.delOk'),
    cancelButtonText: t('common.delCancel'),
    type: 'warning'
  })
    .then(async () => {
      let res = await ucRoleBatchDelApi({ ids: ids.join(',') })
        .catch(() => {})
        .finally(() => {
          delLoading.value = false
        })
      if (res) {
        getList()
      }
    })
    .catch(() => {})
}

const actionType = ref('')

const action = async (type: string, row: TableData = {}) => {
  actionType.value = type
  let treeRes: any
  let res: any
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0'
      }
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'function': // 功能权限
      dialogTitle.value = '功能权限'
      tableObject.currentRow = row
      dialogVisible.value = true
      treeProps.value = {
        children: 'children',
        label: 'fa_name'
      }
      treeKey.value = 'fa_id'
      treeRes = await ucFaListApi({})
        .catch(() => {})
        .finally(() => {})
      if (treeRes) {
        treeData.value = treeRes.data
      }
      // 查询出该角色的菜单权限
      res = await ucRoleFaSeeApi({ role_id: row.role_id })
        .catch(() => {})
        .finally(() => {})
      if (res) {
        let ids: any = []
        res.data.forEach((item) => {
          ids.push(item.fa_id)
        })
        const tree = unref(treeRef)
        tree!.setCheckedKeys(ids)
      }
      break
    case 'del':
      ElMessageBox.confirm('确定要删除这个角色吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log(11112)
          apiDel(row.role_id)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    default:
      console.log('未知类型')
  }
}

const apiDel = async (role_id) => {
  let delRes = await ucRoleDelAdminApi({ role_id: role_id })
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
  if (delRes) {
    getList()
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()

const treeRef = ref<ComponentRef<typeof Tree>>()

const loading = ref(false)

const save = async () => {
  const edit = unref(editRef)
  const tree = unref(treeRef)
  let treeChecked: any
  let data: any
  let res: any
  switch (actionType.value) {
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as TableData
          let res = await ucRoleEditAdminApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })

      break
    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as TableData
          let res = await ucRoleAddApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    case 'function':
      loading.value = true
      treeChecked = tree?.getCheckedNodes()
      data = { role_id: tableObject.currentRow!.role_id, set: [] }
      treeChecked.forEach((item) => {
        data.set.push({
          fa_id: item.fa_id,
          fa_code: item.fa_code,
          authority: '1'
        })
      })
      res = await ucRoleFaSetApi(data)
        .catch(() => {})
        .finally(() => {})
      if (res) {
        ElMessage({
          showClose: true,
          message: res.msg,
          type: 'success'
        })
        loading.value = false
        dialogVisible.value = false
      }
      break
    default:
      console.log('未知类型')
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
      <ElButton :loading="delLoading" type="danger" @click="delData()"> 批量删除 </ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton
          type="primary"
          :icon="iconEdit"
          circle
          @click="action('edit', row)"
          title="编辑"
        />
        <ElButton type="success" :icon="iconSee" circle @click="action('see', row)" title="详情" />
        <ElButton
          type="warning"
          :icon="iconFunction"
          circle
          @click="action('function', row)"
          title="功能权限"
        />
        <ElButton type="danger" :icon="iconDel" circle @click="action('del', row)" title="删除" />
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit
      v-if="actionType == 'edit' || actionType == 'add'"
      ref="editRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />

    <Tree
      v-if="actionType == 'function'"
      :treeProps="treeProps"
      :treeData="treeData"
      :nodeKey="treeKey"
      ref="treeRef"
    />

    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="loading" @click="save()">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
